<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="88px"
      class="globalSerchFormStyle"
    >
      <el-row>
        <!-- <el-col :span="6">
          <el-form-item label="是否使用" prop="couponIsUsed">
            <el-select
              v-model="queryParams.couponIsUsed"
              placeholder="油品名称"
              clearable
              size="small"
              style="width: 190px"
            >
              <el-option
                v-for="dict in oilNameOptions"
                :key="dict.dictLabel"
                :label="dict.dictLabel"
                :value="dict.dictLabel"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="使用状态" prop="couponIsUsed">
            <el-select
              v-model="queryParams.couponIsUsed"
              clearable
              placeholder="请选择"
              size="small"
              style="width: 180px"
            >
              <el-option label="已使用" value="1"></el-option>
              <el-option label="未使用" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="核销手机号" prop="verificationUserPhone">
            <el-input
              v-model="queryParams.verificationUserPhone"
              placeholder="请输入手机号"
              clearable
              size="small"
              style="width: 180px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户手机号" prop="mobilePhone">
            <el-input
              v-model="queryParams.mobilePhone"
              placeholder="请输入手机号"
              clearable
              size="small"
              style="width: 180px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="领取时间" prop="couponGetTime">
            <el-date-picker
              style="width: 180px"
              v-model="dateRangeCreatedDate"
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="collapse">
        <el-col :span="6">
          <el-form-item label="核销时间" prop="verificationTime">
            <el-date-picker
              style="width: 180px"
              v-model="dateRangeverificationTime"
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="有效状态" prop="couponIsEffective">
            <el-select
              v-model="queryParams.couponIsEffective"
              placeholder="请选择"
              size="small"
              style="width: 180px"
            >
              <el-option label="生效中" value="1"></el-option>
              <el-option label="已生效" value="3"></el-option>
              <el-option label="已过期" value="0"></el-option>
              <el-option label="已作废" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发放类型" prop="activityType">
            <el-select
              v-model="queryParams.activityType"
              placeholder="请选择"
              size="small"
              style="width: 180px"
            >
              <el-option label="手动领取" value="0"></el-option>
              <el-option label="支付成功后发放" value="1"></el-option>
              <el-option label="充值发放" value="2"></el-option>
              <el-option label="手动发放" value="4"></el-option>
              <el-option label="注册发放" value="5"></el-option>
              <el-option label="兑换商品" value="6"></el-option>
              <el-option label="超级会员开通发放" value="7"></el-option>
              <el-option label="秒杀活动" value="8"></el-option>
              <el-option label="推荐成功后发放" value="9"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮 -->
    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          id="closeSearchBtn"
          @click="
            (closeSearch) => {
              collapse = !collapse;
            }
          "
        >
          {{ collapse ? "收起" : "展开更多" }}
          <i :class="collapse ? 'el-icon-arrow-up ' : 'el-icon-arrow-down'"></i>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          size="mini"
          @click="openMessageBatch"
          :disabled="voidDisabled"
          >批量作废</el-button
        >
      </el-col>
    </el-row>

    <el-row style="margin: 10px 0px 15px 0px; font-size: 13px">
      <el-col :span="3">
        <div class="grid-purple">
          <span>合计：</span>
          <span style="color: #409eff">{{ sumUpInfo.totalCount }}</span>
          <span style="color: #409eff"> 张 </span>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="grid-purple">
          <span>生效中：</span>
          <span style="color: #409eff">{{ sumUpInfo.effectiveCount }}</span>
          <span style="color: #409eff"> 张 </span>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="grid-purple">
          <span>已生效：</span>
          <span style="color: #409eff">{{ sumUpInfo.usedCount }}</span>
          <span style="color: #409eff"> 张 </span>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="grid-purple">
          <span>已过期：</span>
          <span style="color: #409eff">{{ sumUpInfo.expiredCount }}</span>
          <span style="color: #409eff"> 张 </span>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="grid-purple" style="border: 0px">
          <span>已作废：</span>
          <span style="color: #409eff">{{ sumUpInfo.deletedCount }}</span>
          <span style="color: #409eff"> 张 </span>
        </div>
      </el-col>
    </el-row>

    <!-- table -->
    <el-table
      :data="couponUserList"
      stripe
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <af-table-column
        type="selection"
        width="60"
        align="left"
      ></af-table-column>

      <af-table-column v-if="false" label="优惠券id" align="left" prop="id" />
      <af-table-column
        label="用户ID"
        align="left"
        prop="unionId"
        v-if="false"
      />
      <af-table-column
        label="油站ID"
        align="left"
        prop="stationId"
        v-if="false"
      />
      <af-table-column
        label="发放方式ID"
        align="left"
        prop="issueId"
        v-if="false"
      />

      <af-table-column label="优惠券名称" align="left" prop="couponRemark" />
      <af-table-column label="发放类型" align="left" prop="issueRemark">
        <template slot-scope="scope">
          {{ scope.row.activityType === 0 ? "手动领取" : "" }}
          {{ scope.row.activityType === 1 ? "支付成功后发放" : "" }}
          {{ scope.row.activityType === 2 ? "充值发放" : "" }}
          {{ scope.row.activityType === 4 ? "手动发放" : "" }}
          {{ scope.row.activityType === 5 ? "注册发放" : "" }}
          {{ scope.row.activityType === 6 ? "兑换商品" : "" }}
          {{ scope.row.activityType === 7 ? "超级会员开通发放" : "" }}
          {{ scope.row.activityType === 8 ? "秒杀活动" : "" }}
          {{ scope.row.activityType === 9 ? "推荐成功后发放" : "" }}
        </template>
      </af-table-column>
      <af-table-column label="活动名称" align="left" prop="activityName" />

      <af-table-column
        label="优惠券ID"
        align="left"
        prop="couponId"
        v-if="false"
      />

      <af-table-column label="优惠内容" align="left">
        <template slot-scope="scope">
          {{
            scope.row.couponType == 1
              ? "现金劵" + "--面值：" + scope.row.couponAmt + "元"
              : ""
          }}
          {{
            scope.row.couponType == 2
              ? "折扣券" + "--折扣：" + scope.row.couponAmt + "% "
              : ""
          }}
          {{
            scope.row.couponType == 3
              ? "兑换券" + "--商品：" + scope.row.couponName
              : ""
          }}
        </template>
      </af-table-column>
      <af-table-column label="使用状态" align="left">
        <template slot-scope="scope">
          {{ scope.row.couponIsUsed == "0" ? "未使用" : "" }}
          {{ scope.row.couponIsUsed == "1" ? "已使用" : "" }}
          {{ scope.row.couponIsUsed == "2" ? "已核销" : "" }}
        </template>
      </af-table-column>
      <af-table-column label="有效状态" align="left">
        <template slot-scope="scope">
          <!-- {{ scope.row.couponIsEffective == "0" ? "无效" : "" }}
          {{ scope.row.couponIsEffective == "1" ? "有效" : "" }} -->
          <span class="expired-state-color">
            {{ scope.row.couponIsEffective === "0" ? "已过期" : "" }}
          </span>
          <span class="effect-state-color">
            {{ scope.row.couponIsEffective === "1" ? "生效中" : "" }}
          </span>
          <span class="cancelled-state-color">
            {{ scope.row.couponIsEffective === "2" ? "已作废" : "" }}
          </span>
          <span class="took-effect-state-color">
            {{ scope.row.couponIsEffective === "3" ? "已生效" : "" }}
          </span>
        </template>
      </af-table-column>
      <af-table-column
        label="用户保存id"
        align="left"
        prop="userId"
        v-if="false"
      />
      <af-table-column label="用户手机号" align="left" prop="mobilePhone" />
      <af-table-column label="用户名" align="left" prop="blogNickName" />
      <af-table-column
        label="核销员账号"
        align="left"
        prop="verificationUserAccount"
      />
      <af-table-column label="获取时间" align="left" prop="couponGetTime" />
      <af-table-column label="核销时间" align="left" prop="verificationTime" />

      <af-table-column label="作废时间" align="left">
        <template slot-scope="scope">
          {{ scope.row.invalidTime }}
        </template>
      </af-table-column>
      <af-table-column label="操作" align="left" fixed="right">
        <template slot-scope="scope">
          <span
            v-show="scope.row.couponIsEffective === '1'"
            @click="openMessageVoid(scope.row)"
            style="color: #02a7f0; cursor: pointer"
          >
            作废
          </span>
        </template>
      </af-table-column>

      <!-- <af-table-column label="优惠券获取时间" align="left" prop="getCouponTime">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.getCouponTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </af-table-column>
      <af-table-column label="优惠券截止时间" align="left" prop="couponEffectiveTime">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.couponEffectiveTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </af-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script>
import { timeComparison } from "@/utils/timeConversion";
import { listOrder, exportOrder, printOrderInfo } from "@/api/station/order";
import { stationinfo } from "@/api/station/gun";
import { listPrice, getPrice } from "@/api/station/price";
import { getSumCouponUser } from "@/api/coupon/info";
import { queryCouponUserList, expexportCouponUser } from "@/api/coupon";
import { listManage } from "@/api/station/manage";
import { cancelTheCoupon, batchVoid } from "@/api/coupon/creation";

export default {
  name: "coupon_user",
  data() {
    return {
      // 合计
      sumUpInfo: {},
      //创建订单时间间隔
      dateRangeCreatedDate: [],
      dateRangeverificationTime: [],
      // 总条数
      total: 0,
      // 优惠券的信息
      couponUserList: [],
      oilNameOptions: [],
      // 字典
      payTypeOptions: [],
      // 下拉油站
      stationOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        levelId: this.levelId,
        pageNum: 1,
        pageSize: 10,
        issueId: null,
        couponId: null,
        stationId: null,
        couponIsUsed: null,
        getCouponTime: null,
        verificationUserPhone: null,
        mobilePhone: null,
        verificationEndTime: null,
        verificationBeginTime: null,
        // 有效状态，
        couponIsEffective: null,
        // 发放类型
        activityType: null,
      },
      // 表单校验
      rules: {},
      reprint: false,
      collapse: false,

      // 表单多选框数组Id
      multipleSelectionId: [],
      // 批量作废按钮禁用状态约束之一,勾选的必须包含一个可以作废的选项
      voidOrNot: [],
      loading: false,
    };
  },
  created() {
    this.getList();
    this.sumUp();
  },

  methods: {
    // 查询汇总合计生效
    sumUp() {
      this.queryParams.levelId = this.levelId;
      if (
        this.dateRangeverificationTime != null &&
        this.dateRangeverificationTime.length > 0
      ) {
        this.queryParams.verificationBeginTime =
          this.dateRangeverificationTime[0];
        this.queryParams.verificationEndTime =
          this.dateRangeverificationTime[1];
      } else {
        this.queryParams.verificationBeginTime = null;
        this.queryParams.verificationEndTime = null;
      }

      getSumCouponUser(
        this.addDateRange(this.queryParams, this.dateRangeCreatedDate)
      ).then((res) => {
        this.sumUpInfo = res;
      });
    },
    /** 查询订单支付列表 */
    getList() {
      this.loading = true;
      this.queryParams.levelId = this.levelId;
      if (
        this.dateRangeverificationTime != null &&
        this.dateRangeverificationTime.length > 0
      ) {
        this.queryParams.verificationBeginTime =
          this.dateRangeverificationTime[0];
        this.queryParams.verificationEndTime =
          this.dateRangeverificationTime[1];
      } else {
        this.queryParams.verificationBeginTime = null;
        this.queryParams.verificationEndTime = null;
      }

      const queryParams = this.addDateRange(
        this.queryParams,
        this.dateRangeCreatedDate
      );

      // const time = timeComparison(
      //   "earching",
      //   queryParams.beginTime,
      //   queryParams.endTime,
      //   queryParams.verificationBeginTime,
      //   queryParams.verificationEndTime
      // );
      // if (!time) return (this.loading = false);

      queryCouponUserList(queryParams)
        .then((response) => {
          this.couponUserList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.sumUp();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreatedDate = [];
      this.dateRangeverificationTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 导出按钮操作 */
    handleExport() {
      if (
        this.dateRangeverificationTime != null &&
        this.dateRangeverificationTime.length > 0
      ) {
        this.queryParams.verificationBeginTime =
          this.dateRangeverificationTime[0];
        this.queryParams.verificationEndTime =
          this.dateRangeverificationTime[1];
      } else {
        this.queryParams.verificationBeginTime = null;
        this.queryParams.verificationEndTime = null;
      }
      const queryParams = this.addDateRange(
        this.queryParams,
        this.dateRangeCreatedDate
      );

      // const time = timeComparison(
      //   "export",
      //   queryParams.beginTime,
      //   queryParams.endTime,
      //   queryParams.verificationBeginTime,
      //   queryParams.verificationEndTime
      // );
      // if (!time) return;

      this.$confirm("是否确认导出所有优惠券数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return expexportCouponUser(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    // 点击操作的作废，然后弹出确认框确认是否作废
    openMessageVoid(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("hr"),
          h("span", null, "确认作废该优惠卷吗？"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            await cancelTheCoupon(row.id);
            this.getList();
            done();
          } else {
            done();
          }
        },
      })
        .then((action) => {
          // 点击操作的作废，然后弹出确认框确认是否作废,点击确认之后弹出信息提示
          // this.$message({
          //   type: 'info',
          //   message: 'action: ' + action
          // });
        })
        .catch((action) => {
          // 点击操作的作废，然后弹出取消框确认是否作废,点击取消之后弹出信息提示
          // this.$message({
          //   type: 'info',
          //   message: 'action: ' + action
          // });
        });
    },

    // 点击批量作废优惠卷，然后弹出确认框确认是否作废
    openMessageBatch() {
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("hr"),
          h("span", null, `确认作废${this.voidOrNot.length}张优惠卷吗？`),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            await batchVoid(this.multipleSelectionId);
            this.getList();
            done();
          } else {
            done();
          }
        },
      })
        .then((action) => {})
        .catch((action) => {});
    },

    // 表格多选框被点击触发函数
    handleSelectionChange(val) {
      // 筛选所有有效状态为生效中的数据
      this.voidOrNot = val.filter((item) => {
        return item.couponIsEffective === "1";
      });
      this.multipleSelectionId = this.voidOrNot.map((item) => {
        return item.id;
      });
    },
  },

  computed: {
    // 控制批量作废按钮
    voidDisabled() {
      return (
        this.multipleSelectionId.length === 0 || this.voidOrNot.length === 0
      );
    },
  },
};
</script>
<style scoped lang="scss">
.grid-purple {
  // border: 2px solid firebrick;
  border-right: 1px solid rgba(151, 151, 151, 0.651);
  margin-right: 20%;
}
</style>
